import {
    _decorator,
    animation,
    Animation,
    AnimationClip,
    Component,
    Node,
    resources,
    Sprite,
    SpriteFrame,
    UITransform,
} from "cc";
import { CONTROLLER_ENUM, DIRECTION_ENUM, DIRECTION_ORDER_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_TYPE, PARAMS_NAME_ENUM } from "../Enums";
import { EntityManager } from "../Base/EntityManager";
import DataManager from "../Runtime/DataManager";
import EventManager from "../Runtime/EventManager";
import { IEntity } from "../Levels";
const { ccclass, property } = _decorator;

@ccclass("EnemyManager")
export class EnemyManager extends EntityManager {

    async init(params: IEntity) {
        super.init(params);

        EventManager.Instance.on(EVENT_TYPE.PLAYER_BORNED, this.changeDirectionOnPlayerMoved, this);
        EventManager.Instance.on(EVENT_TYPE.PLAYER_MOVE_END, this.changeDirectionOnPlayerMoved, this);
        EventManager.Instance.on(EVENT_TYPE.ATTACH_ENEMY, this.onDead, this);
        this.changeDirectionOnPlayerMoved(true);
    }

    protected onDestroy(): void {
        super.onDestroy();
        EventManager.Instance.off(EVENT_TYPE.PLAYER_BORNED, this.changeDirectionOnPlayerMoved);
        EventManager.Instance.off(EVENT_TYPE.PLAYER_MOVE_END, this.changeDirectionOnPlayerMoved);
        EventManager.Instance.off(EVENT_TYPE.ATTACH_ENEMY, this.onDead);
    }

    update() {
        super.update();
    }

    changeDirectionOnPlayerMoved(isInit: boolean = false) {
        if (!DataManager.Instance.player) {
            return
        }

        if (this.state === ENTITY_STATE_ENUM.DEATH) {
            return;
        }

        const { x: playerX, y: playerY } = DataManager.Instance.player;

        const disX = Math.abs(this.x - playerX);
        const disY = Math.abs(this.y - playerY);

        if (disX === disY && !isInit) {
            return;
        }

        console.log(this);

        if (playerX >= this.x && playerY <= this.y) {
            this.direction = disY > disX ? DIRECTION_ENUM.UP : DIRECTION_ENUM.RIGHT;
        } else if (playerX <= this.x && playerY <= this.y) {
            this.direction = disY > disX ? DIRECTION_ENUM.UP : DIRECTION_ENUM.LEFT;
        } else if (playerX <= this.x && playerY >= this.y) {
            this.direction = disY > disX ? DIRECTION_ENUM.DOWN : DIRECTION_ENUM.LEFT;
        } else if (playerX >= this.x && playerY >= this.y) {
            this.direction = disY > disX ? DIRECTION_ENUM.DOWN : DIRECTION_ENUM.RIGHT;
        }
    }

    onDead(id: string) {
        if (this.state === ENTITY_STATE_ENUM.DEATH) {
            return;
        }

        if (this.id === id) {
            this.state = ENTITY_STATE_ENUM.DEATH;
        }
    }
}
